#!/bin/bash

user=`id -nu`
group=`id -ng`
uid=`id -u`
gid=`id -g`
name=cw4pa
version=10.5.1
macaddr=02:42:ac:aa:00:02
ssh_port=20320
vnc_port=20321

cmd=
while [ $# -ne 0 ]; do
	case $1 in
	*=*)
		eval ${1%%=*}=${1#*=}
		shift
		;;
	*)
		cmd=$1
		shift
		;;
	esac
done

repo=`tr '[:upper:]' '[:lower:]' <<< ${user}`_${name}
workdir=$HOME/$name

case $cmd in
build)
	mkdir -p $HOME/$name
	export DOCKER_BUILDKIT=0
	docker build -t $repo:$version \
		--build-arg=APT_MIRROR_URL='mirrors.ustc.edu.cn' \
		--ulimit nofile=32768 --ulimit stack=-1 \
		--network=bridge ${0%/*}
	;;
run)
	docker run -dt -P -h $name --add-host $name:127.0.0.1 --name=${repo}_${version} -p $ssh_port:22 -p $vnc_port:5900 \
		--privileged=true --ulimit nofile=32768 --ulimit stack=-1 \
		-e _INIT_USER=$user -e _INIT_GROUP=$group -e _INIT_UID=$uid -e _INIT_GID=$gid -e _INIT_WORKDIR=$workdir \
		-v $workdir:$workdir -v /dev/bus/usb:/dev/bus/usb --network=bridge --mac-address=$macaddr $repo:$version
	;;
start)
	docker start ${repo}_${version}
	;;
stop)
	docker stop ${repo}_${version} -t 1
	;;
sh)
	docker exec -it -u $user ${repo}_${version} bash
	;;
status)
	docker ps -f "name=${repo}_${version}"
	;;
ssh)
	ssh $user@${ip-172.17.0.1} -p `docker port ${repo}_${version} 22/tcp | sed -ne 's/^0.0.0.0://p'` \
		-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o TCPKeepAlive=yes
	;;
cwtap)
	if [ -z "$dev" ]; then
		echo "ERR: \"dev\" not specified" >&2
		exit 1
	fi
	sudo $SHELL -c "dhclient -r $dev 2>/dev/null && dhclient $dev -v 2>&1 | sed -ne 's/DHCPACK.*from /cwtap=/p'"
	;;
*)
	echo "ERR: unknown command \"$cmd\"" >&2
	exit 1
	;;
esac
